const app = getApp()
const api = require('../../utils/api')
import * as echarts from '../../ec-canvas/echarts'

function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr
  })
  canvas.setChart(chart)

  const targetWeight = app.globalData.userInfo?.targetWeight || 65

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const data = params[0]
        const diff = (data.value - targetWeight).toFixed(1)
        return `${data.name}<br/>
                体重: ${data.value} kg<br/>
                目标差值: ${diff > 0 ? '+' + diff : diff} kg`
      }
    },
    grid: {
      top: 30,
      bottom: 30,
      left: 40,
      right: 20
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: [],
      axisLine: { lineStyle: { color: '#999' } }
    },
    yAxis: {
      type: 'value',
      splitLine: { lineStyle: { color: '#eee' } },
      axisLine: { lineStyle: { color: '#999' } },
      axisLabel: {
        formatter: '{value} kg'
      }
    },
    series: [{
      type: 'line',
      smooth: true,
      data: [],
      markLine: {
        silent: true,
        data: [{
          yAxis: targetWeight,
          label: { formatter: '目标体重' },
          lineStyle: { color: '#9C6AD9' }
        }]
      },
      itemStyle: {
        color: '#6E8FD9'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
          offset: 0,
          color: 'rgba(110, 143, 217, 0.3)'
        }, {
          offset: 1,
          color: 'rgba(110, 143, 217, 0.1)'
        }])
      }
    }]
  }

  chart.setOption(option)
  return chart
}

Page({
  data: {
    timeRange: 'day', // day, week, month
    showDayView: true,
    showWeekView: false,
    showMonthView: false,
    currentDate: '',
    today: '',           // YYYY-MM-DD 格式
    selectedDateStr: '', // YYYY-MM-DD 格式
    selectedDate: null,  // 存储选中的日期对象
    bmiLevel: '--',
    bmiClass: '',
    todayRecords: [],
    chartData: [],
    xLabels: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
    statistics: {
      average: '--',
      max: '--',
      min: '--',
      totalChange: '--'
    },
    ec: {
      lazyLoad: true,
      disableTouch: false
    },
    weekEc: {
      lazyLoad: true,
      disableTouch: false,
      onInit: initChart
    },
    monthEc: {
      lazyLoad: true,
      disableTouch: false,
      onInit: initChart
    },
    lastFetchTime: null,
    needRefresh: true,
    cachedData: {
      day: {},
      week: {},
      month: {}
    },
    useSimpleChart: true,
    targetWeight: 65, // 默认目标体重，可从用户信息中获取
    userHeight: 170  // 默认身高，用于计算BMI
  },

  onLoad() {
    // 获取用户信息中的目标体重和身高
    if (app.globalData.userInfo) {
      this.setData({
        targetWeight: app.globalData.userInfo.targetWeight || 65,
        userHeight: app.globalData.userInfo.height || 170,
        needRefresh: false // 默认不需要刷新数据
      })
    }
    
    this.initDates()
  },

  onShow() {
    console.log('weightDetail onShow')
    
    // 初始化日期（如果需要）
    if (!this.data.selectedDateStr) {
      this.initDates()
    }
    
    // 设置强制刷新标志
    wx.setStorageSync('weight_detail_needs_refresh', true);
    
    // 强制刷新机制 - 每次显示页面时都强制刷新数据
    this.setData({ 
      needRefresh: true,
      lastFetchTime: null 
    });
    this.clearAllCache();
    
    // 立即刷新数据 
    this.fetchData();
  },

  initDates() {
    const now = new Date()
    const today = now.toISOString().split('T')[0]  // YYYY-MM-DD 格式
    const currentDate = this.formatDateToString(now)
    
    this.setData({
      today,
      selectedDateStr: today,
      currentDate,
      selectedDate: now
    })
  },

  formatDateToString(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${year}年${month}月${day}日`
  },

  onSelectDate(e) {
    const date = e.detail.value
    const selectedDate = new Date(date)
    const currentDate = this.formatDateToString(selectedDate)
    
    // 如果选择了不同的日期，需要刷新数据
    const needRefresh = date !== this.data.selectedDateStr
    
    this.setData({
      currentDate,
      selectedDateStr: date,
      selectedDate,
      needRefresh
    }, () => {
      // 只有需要刷新时才获取数据
      if (needRefresh) {
        this.fetchData()
      }
    })
  },

  async fetchData() {
    try {
      const { timeRange, selectedDateStr } = this.data
      console.log(`[WeightDetail] 开始获取${timeRange}数据，选择日期: ${selectedDateStr}`)
      
      // 检查缓存
      const cacheKey = `${timeRange}_${selectedDateStr}`
      if (this.data.cachedData[timeRange][cacheKey]) {
        // 使用缓存数据
        console.log('[WeightDetail] 使用缓存数据')
        const cachedData = this.data.cachedData[timeRange][cacheKey]
        this.updateViewWithData(timeRange, cachedData)
        return
      }

      const startDate = new Date(selectedDateStr)
      startDate.setHours(0, 0, 0, 0)
      
      let endDate = new Date(startDate)
      // 根据时间范围设置不同的日期范围
      switch(timeRange) {
        case 'week':
          // 获取本周的数据
          startDate.setDate(startDate.getDate() - startDate.getDay()) // 设置为本周日
          endDate = new Date(startDate)
          endDate.setDate(startDate.getDate() + 7)
          break
        case 'month':
          // 获取本月的数据
          startDate.setDate(1) // 设置为本月第一天
          endDate = new Date(startDate.getFullYear(), startDate.getMonth() + 1, 1)
          break
        default: // day
          endDate.setDate(startDate.getDate() + 1)
          break
      }
      
      console.log(`[WeightDetail] 查询时间范围: ${startDate.toISOString()} 至 ${endDate.toISOString()}`)

      const records = await api.health.getRecords({ 
        type: 'weight',
        startDate: startDate.toISOString(),
        endDate: endDate.toISOString()
      })
      
      console.log(`[WeightDetail] 获取到${records.length}条记录`, records)

      // 缓存数据
      this.setData({
        [`cachedData.${timeRange}.${cacheKey}`]: records,
        lastFetchTime: Date.now() // 记录最后获取数据的时间戳
      })

      // 更新视图
      this.updateViewWithData(timeRange, records)

    } catch (err) {
      console.error('获取记录失败:', err)
      wx.showToast({
        title: '暂无数据',
        icon: 'none',
        duration: 2000
      })
    }
  },

  updateViewWithData(timeRange, records) {
    if (timeRange === 'day') {
      this.updateDayView(records)
    } else if (timeRange === 'week') {
      this.updateWeekView(records)
    } else { // month
      this.updateMonthView(records)
    }
    
    // 标记不需要刷新，因为已经获取了最新数据
    this.setData({ 
      needRefresh: false 
    })
  },

  updateDayView(records) {
    // 处理日视图数据
    if (!records || records.length === 0) {
      this.setData({
        todayRecords: [],
        bmiLevel: '--',
        bmiClass: ''
      });
      return;
    }

    // 格式化数据用于显示，确保按时间倒序排列
    const formattedRecords = records.map(record => {
      // 使用可用的时间字段，优先使用measuredAt
      const timeField = record.measuredAt || record.timestamp;
      let timeStr = '--:--';
      
      try {
        const time = new Date(timeField);
        if (!isNaN(time.getTime())) {
          const hours = time.getHours().toString().padStart(2, '0');
          const minutes = time.getMinutes().toString().padStart(2, '0');
          timeStr = `${hours}:${minutes}`;
        }
      } catch (e) {
        console.error('时间格式化错误:', e);
      }
      
      // 确保体重值是数字类型
      const weightValue = parseFloat(record.value);
      
      // 计算BMI
      const bmi = weightValue / Math.pow(this.data.userHeight / 100, 2);
      
      return {
        ...record,
        value: weightValue.toFixed(1), // 格式化为一位小数
        timeStr: timeStr,
        bmi: parseFloat(bmi.toFixed(1))
      };
    }).sort((a, b) => {
      // 使用可用的时间字段排序
      const aTime = new Date(a.measuredAt || a.timestamp).getTime();
      const bTime = new Date(b.measuredAt || b.timestamp).getTime();
      return bTime - aTime; // 降序排列
    });

    console.log('体重日视图数据处理后:', formattedRecords);

    // 计算BMI评价（使用最新的记录）
    const latestRecord = formattedRecords[0];
    const bmiEvaluation = this.evaluateBMI(latestRecord.bmi);
    
    this.setData({
      todayRecords: formattedRecords,
      bmiLevel: bmiEvaluation.level,
      bmiClass: bmiEvaluation.class
    });
  },

  updateWeekView(records) {
    // 确保records是有效数据
    if (!records) records = []
    
    // 准备7天数据（一周）
    const startDate = new Date(this.data.selectedDateStr)
    startDate.setDate(startDate.getDate() - startDate.getDay()) // 设置为本周日
    
    const weightData = []
    const xLabels = []
    
    // 生成周数据
    for (let i = 0; i < 7; i++) {
      const currentDate = new Date(startDate)
      currentDate.setDate(startDate.getDate() + i)
      const dateString = currentDate.toISOString().split('T')[0]
      
      // 找出当天的记录
      const dayRecords = records.filter(record => {
        // 正确处理时间戳或日期字符串
        const recordDate = new Date(record.measuredAt || record.timestamp);
        
        // 检查是否是同一天 - 比较年、月、日
        return recordDate.getFullYear() === currentDate.getFullYear() &&
               recordDate.getMonth() === currentDate.getMonth() &&
               recordDate.getDate() === currentDate.getDate();
      })
      
      if (dayRecords.length > 0) {
        // 使用当天最后一次测量值
        const latestRecord = dayRecords[dayRecords.length - 1]
        weightData.push(latestRecord.value)
      } else {
        // 没有数据时使用null
        weightData.push(null)
      }
      
      // 格式化X轴标签
      const day = currentDate.getDate()
      const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][currentDate.getDay()]
      xLabels.push(`${day}日`)
    }
    
    // 计算统计数据
    const validWeightData = weightData.filter(v => v !== null)
    
    const statistics = {
      average: validWeightData.length > 0 
        ? parseFloat((validWeightData.reduce((a, b) => a + b, 0) / validWeightData.length).toFixed(1)) 
        : '--',
      max: validWeightData.length > 0 
        ? Math.max(...validWeightData) 
        : '--',
      min: validWeightData.length > 0 
        ? Math.min(...validWeightData) 
        : '--',
      totalChange: validWeightData.length >= 2
        ? parseFloat((validWeightData[validWeightData.length - 1] - validWeightData[0]).toFixed(1))
        : '--'
    }
    
    // 正确格式化图表数据，将简单数组转换为图表组件期望的对象数组格式
    const formattedChartData = [
      {
        name: '体重',
        data: weightData,
        color: '#1890ff'
      }
    ];
    
    this.setData({
      chartData: this.data.useSimpleChart ? formattedChartData : weightData,
      xLabels,
      statistics,
      showDayView: false,
      showWeekView: true,
      showMonthView: false
    })
    
    // 初始化图表
    if (!this.data.useSimpleChart) {
      this.initWeekChart()
    }
  },

  updateMonthView(records) {
    // 确保records是有效数据
    if (!records) records = []
    
    // 计算当月天数
    const year = this.data.selectedDate.getFullYear()
    const month = this.data.selectedDate.getMonth()
    const daysInMonth = new Date(year, month + 1, 0).getDate()
    
    const weightData = []
    const xLabels = []
    
    // 生成月数据
    for (let i = 1; i <= daysInMonth; i++) {
      const currentDate = new Date(year, month, i)
      const dateString = currentDate.toISOString().split('T')[0]
      
      // 找出当天的记录
      const dayRecords = records.filter(record => {
        // 正确处理时间戳或日期字符串
        const recordDate = new Date(record.measuredAt || record.timestamp);
        
        // 检查是否是同一天 - 比较年、月、日
        return recordDate.getFullYear() === year &&
               recordDate.getMonth() === month &&
               recordDate.getDate() === i;
      })
      
      if (dayRecords.length > 0) {
        // 使用当天最后一次测量值
        const latestRecord = dayRecords[dayRecords.length - 1]
        weightData.push(latestRecord.value)
      } else {
        // 没有数据时使用null
        weightData.push(null)
      }
      
      // 格式化X轴标签 - 月视图只显示日期
      xLabels.push(`${i}日`)
    }
    
    // 计算统计数据
    const validWeightData = weightData.filter(v => v !== null)
    
    const statistics = {
      average: validWeightData.length > 0 
        ? parseFloat((validWeightData.reduce((a, b) => a + b, 0) / validWeightData.length).toFixed(1)) 
        : '--',
      max: validWeightData.length > 0 
        ? Math.max(...validWeightData) 
        : '--',
      min: validWeightData.length > 0 
        ? Math.min(...validWeightData) 
        : '--',
      totalChange: validWeightData.length >= 2
        ? parseFloat((validWeightData[validWeightData.length - 1] - validWeightData[0]).toFixed(1))
        : '--'
    }
    
    // 正确格式化图表数据，将简单数组转换为图表组件期望的对象数组格式
    const formattedChartData = [
      {
        name: '体重',
        data: weightData,
        color: '#1890ff'
      }
    ];
    
    this.setData({
      chartData: this.data.useSimpleChart ? formattedChartData : weightData,
      xLabels,
      statistics,
      showDayView: false,
      showWeekView: false,
      showMonthView: true
    })
    
    // 初始化图表
    if (!this.data.useSimpleChart) {
      this.initMonthChart()
    }
  },

  initWeekChart() {
    this.weekChart = this.selectComponent('#weekChart')
    if (this.weekChart) {
      this.weekChart.init((canvas, width, height, dpr) => {
        const chart = initChart(canvas, width, height, dpr)
        
        // 更新图表数据
        const option = {
          xAxis: {
            data: this.data.xLabels
          },
          series: [{
            data: this.data.chartData
          }]
        }
        
        chart.setOption(option)
        return chart
      })
    }
  },
  
  initMonthChart() {
    this.monthChart = this.selectComponent('#monthChart')
    if (this.monthChart) {
      this.monthChart.init((canvas, width, height, dpr) => {
        const chart = initChart(canvas, width, height, dpr)
        
        // 更新图表数据
        const option = {
          xAxis: {
            data: this.data.xLabels
          },
          series: [{
            data: this.data.chartData
          }]
        }
        
        chart.setOption(option)
        return chart
      })
    }
  },

  evaluateBMI(bmi) {
    if (!bmi || isNaN(bmi)) {
      return { 
        level: '--',
        class: ''
      }
    }
    
    // BMI评估标准
    if (bmi < 18.5) {
      return {
        level: '偏瘦',
        class: 'quality-low'
      }
    } else if (bmi >= 18.5 && bmi < 24) {
      return {
        level: '正常',
        class: 'quality-normal'
      }
    } else if (bmi >= 24 && bmi < 28) {
      return {
        level: '超重',
        class: 'quality-high'
      }
    } else {
      return {
        level: '肥胖',
        class: 'quality-high'
      }
    }
  },

  changeTimeRange(e) {
    const timeRange = e.currentTarget.dataset.range
    
    if (timeRange === this.data.timeRange) {
      return // 避免重复切换
    }
    
    // 更新视图状态，与时间范围同步
    this.setData({
      timeRange,
      showDayView: timeRange === 'day',
      showWeekView: timeRange === 'week',
      showMonthView: timeRange === 'month'
    }, () => {
      this.fetchData()
    })
  },

  showBMIInfo() {
    wx.showModal({
      title: 'BMI评价标准',
      content: 'BMI小于18.5：偏瘦\nBMI在18.5-23.9：正常\nBMI在24-27.9：超重\nBMI大于等于28：肥胖',
      showCancel: false
    })
  },

  showWeightChangeInfo() {
    const timeRange = this.data.timeRange;
    const period = timeRange === 'week' ? '周' : '月';
    
    wx.showModal({
      title: `本${period}体重变化说明`,
      content: `体重变化是通过当前${period}内第一次记录与最后一次记录的体重值之差计算得出。\n\n正数表示体重增加，负数表示体重减少。\n\n健康的体重变化建议：\n- 减重：每周不超过0.5-1kg\n- 增重：每周不超过0.25-0.5kg\n\n过快的体重变化可能对健康不利，建议保持稳定的生活方式。`,
      showCancel: false
    })
  },

  onLearnMoreTap() {
    wx.navigateTo({
      url: '/pages/weight/knowledge'
    })
  },

  showActionSheet() {
    wx.showActionSheet({
      itemList: ['数据记录', '手动添加', '体重设置'],
      itemColor: '#333333',
      success: (res) => {
        switch (res.tapIndex) {
          case 0: // 数据记录
            wx.navigateTo({
              url: '/pages/history/history?type=weight',
              events: {
                // 数据变更事件
                dataChanged: (data) => {
                  console.log('收到历史页面数据变更事件:', data);
                  this.forceRefresh();
                }
              },
              success: (res) => {
                res.eventChannel.on('dataChanged', (data) => {
                  console.log('通过事件通道收到历史页面数据变更:', data);
                  this.forceRefresh();
                });
              }
            });
            break;
          case 1: // 手动添加
            wx.navigateTo({
              url: '/pages/record/record?type=weight',
              events: {
                recordAdded: (data) => {
                  console.log('收到记录添加事件:', data);
                  this.forceRefresh();
                }
              },
              success: (res) => {
                res.eventChannel.on('recordAdded', (data) => {
                  console.log('通过事件通道收到记录添加:', data);
                  this.forceRefresh();
                });
              }
            });
            break;
          case 2: // 体重设置
            wx.navigateTo({
              url: '/pages/settings/weightSettings'
            });
            break;
        }
      }
    });
  },

  confirmDelete() {
    wx.showModal({
      title: '删除记录',
      content: '确定要删除当前所有体重记录吗？此操作不可恢复。',
      success: (res) => {
        if (res.confirm) {
          // 执行删除操作
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          })
          // 清空记录并刷新数据
          this.setData({
            todayRecords: [],
            needRefresh: true,
            cachedData: {
              day: {},
              week: {},
              month: {}
            }
          }, () => {
            this.fetchData()
          })
        }
      }
    })
  },

  clearAllCache() {
    console.log('清除所有体重数据缓存');
    this.setData({
      cachedData: {
        day: {},
        week: {},
        month: {}
      },
      lastFetchTime: null
    });
  },

  clearCache(timeRange) {
    if (timeRange) {
      // 清除指定时间范围的缓存
      console.log(`清除体重${timeRange}视图缓存`);
      this.setData({
        [`cachedData.${timeRange}`]: {}
      });
    } else {
      // 如果没有指定时间范围，则调用clearAllCache
      this.clearAllCache();
    }
  },

  // 强制刷新数据
  forceRefresh() {
    console.log('强制刷新体重数据');
    this.clearAllCache();
    this.setData({ 
      needRefresh: true,
      lastFetchTime: null 
    });
    this.fetchData();
  },
})
